<template>
  <view class="page">
    <!-- 顶部标题栏 -->
    <view class="header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="header-title">创建用户</view>
      <view class="header-right"></view>
    </view>

    <!-- 表单区域 -->
    <view class="content">
      <view class="form-card">
        <!-- 用户名 -->
        <view class="form-row">
          <text class="form-label">用户名 <text class="required">*</text></text>
          <input
            class="form-input"
            v-model="formData.username"
            placeholder="请输入用户名"
            @blur="validateUsername"
          />
          <text v-if="errors.username" class="error-tip">{{ errors.username }}</text>
        </view>

        <!-- 密码 -->
        <view class="form-row">
          <text class="form-label">密码 <text class="required">*</text></text>
          <input
            class="form-input"
            v-model="formData.password"
            placeholder="请输入密码"
            password
            @blur="validatePassword"
          />
          <text v-if="errors.password" class="error-tip">{{ errors.password }}</text>
        </view>

        <!-- 确认密码 -->
        <view class="form-row">
          <text class="form-label">确认密码 <text class="required">*</text></text>
          <input
            class="form-input"
            v-model="formData.confirmPassword"
            placeholder="请再次输入密码"
            password
            @blur="validateConfirmPassword"
          />
          <text v-if="errors.confirmPassword" class="error-tip">{{ errors.confirmPassword }}</text>
        </view>

        <!-- 真实姓名 -->
        <view class="form-row">
          <text class="form-label">真实姓名 <text class="required">*</text></text>
          <input
            class="form-input"
            v-model="formData.realName"
            placeholder="请输入真实姓名"
            @blur="validateRealName"
          />
          <text v-if="errors.realName" class="error-tip">{{ errors.realName }}</text>
        </view>

        <!-- 手机号 -->
        <view class="form-row">
          <text class="form-label">手机号</text>
          <input
            class="form-input"
            v-model="formData.phone"
            placeholder="请输入手机号"
            type="number"
            @blur="validatePhone"
          />
          <text v-if="errors.phone" class="error-tip">{{ errors.phone }}</text>
        </view>

        <!-- 邮箱 -->
        <view class="form-row">
          <text class="form-label">邮箱</text>
          <input
            class="form-input"
            v-model="formData.email"
            placeholder="请输入邮箱地址"
            @blur="validateEmail"
          />
          <text v-if="errors.email" class="error-tip">{{ errors.email }}</text>
        </view>

        <!-- 角色 -->
        <view class="form-row">
          <text class="form-label">角色 <text class="required">*</text></text>
          <picker :value="roleIndex" :range="roleOptions" range-key="label" @change="onRoleChange">
            <view class="picker-view" :class="{ error: errors.role }">
              <text>{{ roleOptions[roleIndex].label }}</text>
              <text class="arrow">▼</text>
            </view>
          </picker>
          <text v-if="errors.role" class="error-tip">{{ errors.role }}</text>
          <text class="helper-text">{{ getRoleDesc(roleOptions[roleIndex].value) }}</text>
        </view>

        <!-- 学校（根据角色显示） -->
        <view v-if="needSchool" class="form-row">
          <text class="form-label">所属学校 <text class="required">*</text></text>
          <picker :value="schoolIndex" :range="schoolOptions" range-key="label" @change="onSchoolChange">
            <view class="picker-view" :class="{ error: errors.schoolId }">
              <text>{{ schoolOptions[schoolIndex].label }}</text>
              <text class="arrow">▼</text>
            </view>
          </picker>
          <text v-if="errors.schoolId" class="error-tip">{{ errors.schoolId }}</text>
        </view>

        <!-- 初始状态 -->
        <view class="form-row">
          <text class="form-label">初始状态</text>
          <picker :value="statusIndex" :range="statusOptions" range-key="label" @change="onStatusChange">
            <view class="picker-view">
              <text>{{ statusOptions[statusIndex].label }}</text>
              <text class="arrow">▼</text>
            </view>
          </picker>
          <text class="helper-text">{{ statusOptions[statusIndex].description }}</text>
        </view>

        <!-- 备注 -->
        <view class="form-row">
          <text class="form-label">备注信息</text>
          <textarea
            class="form-textarea"
            v-model="formData.remark"
            placeholder="请输入备注信息（选填）"
            maxlength="200"
          />
          <text class="char-count">{{ (formData.remark || '').length }}/200</text>
        </view>
      </view>
    </view>

    <!-- 底部操作区 -->
    <view class="bottom-bar">
      <button class="cancel-btn" @click="onCancel">取消</button>
      <button
        class="submit-btn"
        :class="{ loading: creating }"
        :disabled="creating"
        @click="onSubmit"
      >
        {{ creating ? '创建中...' : '创建用户' }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { userAPI, type UserCreateRequest } from '@/api/user'

// 状态管理
const creating = ref(false)

// 表单数据
const formData = reactive<UserCreateRequest & {
  confirmPassword?: string
  remark?: string
}>({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  phone: '',
  email: '',
  role: '',
  schoolId: '',
  schoolName: '',
  avatar: '',
  remark: ''
})

// 错误信息
const errors = reactive<Record<string, string>>({})

// 角色选项
const roleOptions = [
  { label: '请选择角色', value: '', description: '请选择用户的角色权限' },
  { label: '超级管理员', value: 'ADMIN', description: '拥有系统全部权限' },
  { label: '学校管理员', value: 'SCHOOL_ADMIN', description: '管理学校的教师和学生' },
  { label: '教师', value: 'TEACHER', description: '管理班级学生和档案' },
  { label: '家长', value: 'PARENT', description: '查看孩子的学习情况' }
]

const roleIndex = ref(0)

// 状态选项
const statusOptions = [
  { label: '正常', value: 'ACTIVE', description: '用户创建后可正常登录' },
  { label: '禁用', value: 'INACTIVE', description: '用户创建后无法登录' }
]

const statusIndex = ref(0)

// 学校选项
const schoolOptions = [
  { label: '请选择学校', value: '', name: '' },
  { label: '第一小学', value: 'school1', name: '第一小学' },
  { label: '第二小学', value: 'school2', name: '第二小学' },
  { label: '第三小学', value: 'school3', name: '第三小学' }
]

const schoolIndex = ref(0)

// 计算属性
const needSchool = computed(() => {
  return ['SCHOOL_ADMIN', 'TEACHER', 'PARENT'].includes(formData.role || '')
})

// 验证函数
const validateUsername = () => {
  if (!formData.username?.trim()) {
    errors.username = '请输入用户名'
  } else if (formData.username.length < 3) {
    errors.username = '用户名至少3个字符'
  } else {
    delete errors.username
  }
}

const validatePassword = () => {
  if (!formData.password) {
    errors.password = '请输入密码'
  } else if (formData.password.length < 6) {
    errors.password = '密码至少6个字符'
  } else {
    delete errors.password
  }
}

const validateConfirmPassword = () => {
  if (!formData.confirmPassword) {
    errors.confirmPassword = '请确认密码'
  } else if (formData.confirmPassword !== formData.password) {
    errors.confirmPassword = '两次密码不一致'
  } else {
    delete errors.confirmPassword
  }
}

const validateRealName = () => {
  if (!formData.realName?.trim()) {
    errors.realName = '请输入真实姓名'
  } else {
    delete errors.realName
  }
}

const validatePhone = () => {
  if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
    errors.phone = '请输入正确的手机号'
  } else {
    delete errors.phone
  }
}

const validateEmail = () => {
  if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    errors.email = '请输入正确的邮箱地址'
  } else {
    delete errors.email
  }
}

const validateForm = (): boolean => {
  // 清空错误
  Object.keys(errors).forEach(key => delete errors[key])

  // 验证必填字段
  if (!formData.username?.trim()) errors.username = '请输入用户名'
  if (!formData.password) errors.password = '请输入密码'
  if (!formData.confirmPassword) errors.confirmPassword = '请确认密码'
  if (!formData.realName?.trim()) errors.realName = '请输入真实姓名'
  if (!formData.role) errors.role = '请选择角色'
  if (needSchool.value && !formData.schoolId) errors.schoolId = '请选择学校'

  // 格式验证
  validateUsername()
  validatePassword()
  validateConfirmPassword()
  validateRealName()
  validatePhone()
  validateEmail()

  return Object.keys(errors).length === 0
}

// 事件处理
const getRoleDesc = (role: string): string => {
  const roleOption = roleOptions.find(item => item.value === role)
  return roleOption?.description || ''
}

const onRoleChange = (e: any) => {
  roleIndex.value = e.detail.value
  formData.role = roleOptions[roleIndex.value].value
  if (!needSchool.value) {
    formData.schoolId = ''
    schoolIndex.value = 0
  }
}

const onSchoolChange = (e: any) => {
  schoolIndex.value = e.detail.value
  formData.schoolId = schoolOptions[schoolIndex.value].value
  formData.schoolName = schoolOptions[schoolIndex.value].name
}

const onStatusChange = (e: any) => {
  statusIndex.value = e.detail.value
}

const goBack = () => {
  uni.navigateBack()
}

const onCancel = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消创建用户吗？',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack()
      }
    }
  })
}

const onSubmit = async () => {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单', icon: 'none' })
    return
  }

  try {
    creating.value = true

    const createData: UserCreateRequest = {
      username: formData.username,
      password: formData.password,
      realName: formData.realName,
      phone: formData.phone,
      email: formData.email,
      role: formData.role,
      schoolId: formData.schoolId || undefined,
      schoolName: formData.schoolName || undefined
    }

    const response = await userAPI.createUser(createData)

    if (response.code === 200 || response.code === 0) {
      uni.showToast({ title: '创建成功', icon: 'success' })

      // 处理初始状态
      if (statusOptions[statusIndex.value].value === 'INACTIVE') {
        try {
          await userAPI.deactivateUser(response.data.id)
        } catch (e) {
          console.error('设置状态失败:', e)
        }
      }

      setTimeout(() => uni.navigateBack(), 1500)
    }
  } catch (error) {
    console.error('创建失败:', error)
    uni.showToast({ title: '创建失败', icon: 'error' })
  } finally {
    creating.value = false
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.header {
  height: 56px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;

  .header-left {
    width: 50px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;

    .back-icon {
      font-size: 20px;
      color: #333;
      font-weight: bold;
    }
  }

  .header-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .header-right {
    width: 50px;
  }
}

.content {
  flex: 1;
  padding: 16px;
  padding-bottom: 80px;
}

.form-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.form-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 8px;

  .required {
    color: #ff4d4f;
    margin-left: 2px;
  }
}

.form-input {
  width: 100%;
  height: 44px;
  padding: 0 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  background: #fff;

  &:focus {
    border-color: #1890ff;
    outline: none;
  }
}

.picker-view {
  width: 100%;
  height: 44px;
  padding: 0 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;

  &.error {
    border-color: #ff4d4f;
  }

  .arrow {
    color: #999;
    font-size: 12px;
  }
}

.form-textarea {
  width: 100%;
  min-height: 80px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  background: #fff;
  resize: none;
}

.error-tip {
  display: block;
  font-size: 12px;
  color: #ff4d4f;
  margin-top: 4px;
}

.helper-text {
  display: block;
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.char-count {
  display: block;
  font-size: 12px;
  color: #999;
  text-align: right;
  margin-top: 4px;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 64px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  gap: 12px;
  z-index: 99;

  .cancel-btn,
  .submit-btn {
    height: 40px;
    padding: 0 24px;
    border: none;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 80px;
  }

  .cancel-btn {
    background: #f5f5f5;
    color: #666;

    &:active {
      background: #e8e8e8;
    }
  }

  .submit-btn {
    background: #1890ff;
    color: #fff;

    &:active {
      background: #1677ff;
    }

    &.loading {
      opacity: 0.7;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}
</style>